<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind" @submit="submit">
			<uni-forms-item name="username" label="用户名" required>
				<uni-easyinput :isRequire="true" v-model="formData.username" :clearable="false" placeholder="请输入用户名">
					<template #right>
						<text style="margin-left: 6px;color: red;">必填项</text>
					</template>
				</uni-easyinput>

			</uni-forms-item>
			<uni-forms-item name="password" label="初始密码" required>
				<uni-easyinput :isRequire="true" class="require-bg" v-model="formData.password" :clearable="false"
					placeholder="请输入初始密码">
					<template #right>
						<text style="margin-left: 6px;color: red;">必填项</text>
					</template>
				</uni-easyinput>
			</uni-forms-item>
			<!-- 云端数据 -->
			<uni-forms-item label="机构选择" v-if="hasAdmin">
				<uni-data-select class="require-bg" collection="mechanism" :page-size="500"
					field="_id as value, name as text" v-model="mechanism_id" :clear="true" />
			</uni-forms-item>

			<uni-forms-item name="gender" label="性别">
				<uni-data-select v-model="formData.gender" :localdata="enumGenderList.getnder_list">
				</uni-data-select>
			</uni-forms-item>

			<block v-if="cur_role === 'xueshen'">
				<uni-forms-item name="student_name" label="姓名" required>
					<uni-easyinput class="require-bg" :isRequire="true" v-model="formData.student_name"
						:clearable="false" placeholder="请输入姓名">
						<template #right>
							<text style="margin-left: 6px;color: red;">必填项</text>
						</template>
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="id_card" label="身份证">
					<uni-easyinput v-model="formData.id_card" :clearable="false" type="idcard" placeholder="请输入身份证" />
				</uni-forms-item>
				<uni-forms-item name="tuition" label="学费">
					<uni-easyinput v-model="formData.tuition" type="digit" :clearable="false" placeholder="请输入学费" />
				</uni-forms-item>

				<uni-forms-item name="use_times" label="使用次数" required>
					<uni-easyinput class="require-bg" :isRequire="true" v-model="formData.use_times" type="number"
						:clearable="false" placeholder="请输入使用次数">
						<template #right>
							<text style="margin-left: 6px;color: red;">必填项</text>
						</template>
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="recommender" label="推荐人">
					<uni-easyinput v-model="formData.recommender" :clearable="false" placeholder="推荐人" />
				</uni-forms-item>

				<uni-forms-item name="recommender_mobile" label="推荐人电话">
					<uni-easyinput v-model="formData.recommender_mobile" :clearable="false" placeholder="推荐人电话" />
				</uni-forms-item>

				<uni-forms-item name="test_times" label="考试时间">
					<uni-datetime-picker :isRequire="true" returnType="timestamp" v-model="formData.test_times">
						<template #right>
							<text style="margin-left: 6px;color: red;">必填项</text>
						</template>
					</uni-datetime-picker>
				</uni-forms-item>

				<uni-forms-item name="fee_status" label="学生状态">
					<uni-data-select :isRequire="true" v-model="formData.fee_status"
						:localdata="enumConverterStudent.status_valuetotext">
						<template #right>
							<text style="color: red;">必填项</text>
						</template>
					</uni-data-select>
				</uni-forms-item>

				<uni-forms-item name="type_subject_id" label="科目类型">
					<uni-data-select :isRequire="true" v-model="formData.type_subject_id" required
						collection="type-subject" field="s_id as value, name as text">
						<template #right>
							<text style="color: red;">必填项</text>
						</template>
					</uni-data-select>
				</uni-forms-item>



				<uni-forms-item name="type_drive_id" label="驾驶证类型">
					<uni-data-select :isRequire="true" v-model="formData.type_drive_id" ref="drive_udb"
						@change="setCertValue" collection="type-drive,type-cert"
						field="s_id as value, name as text,_id,type_cert_id">
						<template #right>
							<text style="color: red;">必填项</text>
						</template>
					</uni-data-select>
				</uni-forms-item>


				<uni-forms-item name="type_cert_id" label="证件类型">

					<text>
						{{showCertText}}
					</text>
					<uni-easyinput v-model="formData.type_cert_id" style="visibility:hidden">

					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="subject_page_ids" label="题库">

					<view v-if="formData.type_cert_id!=''" style="display: flex;width:400px;flex-direction: row;flex-wrap: wrap;">
					<!-- 	<uni-data-checkbox :multiple="true" @change="changeQuesction"	
						 @init="getInit"
						 v-model="formData.subject_page_ids" :localdata="subjectList"
							:page-size="500">
						</uni-data-checkbox> -->
						<view v-for="(item,index) in subjectList" style="margin:4px">
							<view style="display: inline-block;" @click="changeSubject(item)">
								<radio  :value="item.name" :checked="formData.subject_page_ids.includes(item.value)">
								</radio>
								<span>{{item.text}}</span>
							</view>
						</view>
					</view>

				</uni-forms-item>
				<uni-forms-item name="comment" label="备注">
					<uni-easyinput v-model="formData.comment" type="textarea" maxlength='-1'></uni-easyinput>
				</uni-forms-item>


			</block>


			<!-- 
			<uni-forms-item name="role" label="角色列表" class="flex-center-x">
				<uni-data-checkbox multiple :localdata="roles" v-model="formData.role" />
			</uni-forms-item> -->

			<!-- 		<uni-forms-item name="dcloud_appid" label="可登录应用" labelWidth="100" class="flex-center-x">
				<uni-data-checkbox :multiple="true" v-model="formData.dcloud_appid" :where="appwhere"
					collection="opendb-app-list" field="appid as value, name as text"></uni-data-checkbox>
			</uni-forms-item>
 -->
			<uni-forms-item name="mobile" label="手机号">
				<uni-easyinput v-model="formData.mobile" :clearable="false" placeholder="请输入手机号" />
			</uni-forms-item>

			<uni-forms-item name="email" label="邮箱">
				<uni-easyinput v-model="formData.email" :clearable="false" placeholder="请输入邮箱" />
			</uni-forms-item>

			<uni-forms-item name="status" label="是否启用" v-if="cur_role==='xueshen'?false:true">
				<switch @change="binddata('status', $event.detail.value)" :checked="formData.status" />
			</uni-forms-item>

			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button"
					@click="submitForm">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;"
						class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator,
		enumConverterStudent,
		enumConverterGender,
		enumGenderList
	} from '@/js_sdk/validator/uni-id-users.js';
	import mCheckbox from './compoents/m-checkbox.vue'
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'uni-id-users';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		components:{
			mCheckbox
		},
		data() {
			return {
				enumGenderList,
				enumConverterGender,
				enumConverterStudent,
				formData: {
					"username": "",
					"password": "",
					"role": ['xueshen'],
					"dcloud_appid": ['__UNI__84671FB'],
					"tags": [],
					"mobile": "",
					"email": "",
					"status": true, //默认启用
					"type_subject_id": "",
					"type_drive_id": "",
					"type_cert_id": "",
					"comment": "",
					"id_card": "",
					"tuition": 0,
					"test_times": 0,
					"fee_status": 0,
					"use_times": 0,
					"recommender": "",
					"recommender_mobile": "",
					"student_name": "",
					"subject_page_ids": [],
					"gender": 0
				},
				subjectPageList: [],
				rules: {
					...getValidator(["username", "password", "role", "mobile", "email"]),
					"status": {
						"rules": [{
							"format": "bool"
						}]
					}
				},
				showCertText: '',
				roles: [{
					value: "xueshen",
					text: "学员"
				}],
				mechanism_id: '',
				roleList: [],
				appwhere: {},
				cur_role: '',
				subjectList: [],
				hasAdmin: false,
				subjectListCache: [],
				lastCacheList: [],
				firstChange: true
				
			}
		},
		onLoad(params) {
			this.formData={
				"username": "",
				"password": "",
				"role": ['xueshen'],
				"dcloud_appid": ['__UNI__84671FB'],
				"tags": [],
				"mobile": "",
				"email": "",
				"status": true, //默认启用
				"type_subject_id": "",
				"type_drive_id": "",
				"type_cert_id": "",
				"comment": "",
				"id_card": "",
				"tuition": 0,
				"test_times": 0,
				"fee_status": 0,
				"login_times":0,
				"use_times": 0,
				"recommender": "",
				"recommender_mobile": "",
				"student_name": "",
				"subject_page_ids": [],
				"gender": 0
			}
			
			if (this.uniIDHasRole('admin') || this.uniIDHasRole('XZID')) {
				this.hasAdmin = true
			}

			if (params.mechanism) {
				this.mechanism_id = params.mechanism
				//this.roleList.push(params.role)

				// if (params.role == 'xueshen') {
				// 	this.appwhere = {
				// 		name: '练习系统'
				// 	}
				// 	this.cur_role = 'xueshen'

				// } else {
				// 	this.appwhere = {
				// 		name: 'PC'
				// 	}
				// }
			}
			this.cur_role = 'xueshen'
			this.appwhere = {
				name: '练习系统'
			}
			//this.loadroles()
		},
		watch: {
			"formData.type_cert_id": function(nv, ov) {
				console.log(nv, ov)
				if (nv) {
					this.getSubjectList()
				}
			},
			"formData.type_subject_id": function(nv) {

				if (this.formData.type_drive_id && this.formData.type_cert_id) {
					this.getSubjectList()
				}
			},
		
		},
		computed: {
			// getPaperWhere() {
			// 	console.log(this.formData.type_subject_id, this.formData.type_drive_id)
			// 	let where = {
			// 		['subject_id.type_subject']: db.command.eq(this.formData.type_subject_id),
			// 		['subject_id.type_drive_id']: db.command.in([this.formData.type_drive_id])
			// 	}
			// 	return where
			// },
			// getSubjectList() {
			// 	console.log(this.mechanism_id,this.formData.type_subject_id,this.formData.type_drive_id)
			// 	return [
			// 		db.collection('mechanism-subject-list')
			// 		.where({
			// 			mechanism_id: dbCmd.eq(this.mechanism_id),
			// 		})
			// 		.field('_id,subject_id,mechanism_id')
			// 		.getTemp(),
			// 		db.collection('subject-page')
			// 		.where({
			// 			['type_subject']: db.command.eq(this.formData.type_subject_id),
			// 			['type_drive_id']: db.command.in([this.formData.type_drive_id])
			// 		}).getTemp()
			// 	]
			// }
		},
		mounted() {
			console.log(this.enumConverterStudent)
		},
		methods: {
			changeSubject(item){
				if(this.formData.subject_page_ids.includes(item.value)){
					let index = this.formData.subject_page_ids.indexOf(item.value)
					this.formData.subject_page_ids.splice(index,1)
				}else{
					this.formData.subject_page_ids.push(item.value)
				}
			},
			getInit(e) {
				console.log('init',e)
				let temp = [] 
				temp = this.subjectListCache.map(e=>{
					return e 
				})
				this.formData.subject_page_ids = temp 
			},
			findExtraElements(a, b) {
				return a.filter(item => !b.includes(item));
			},
			 findMissingElements(a, b) {
			    return b.filter(item => !a.includes(item));
			},
			changeQuesction(e) {
				const nv = e.detail.value
				
				// if (nv.length > this.lastCacheList.length) {
				// 	const many = this.findExtraElements(nv, this.lastCacheList)
				// 	many.map(d=>{
				// 		this.subjectListCache.push(d)
				// 	})
				// }else{
				// 	const miss = this.findMissingElements(nv,this.lastCacheList)
				// 	let start = this.subjectListCache.indexOf(miss[0])
				// 	this.subjectListCache.splice(start,1)
				// }
				
			
				// this.firstChange = false
			},
			changePageIds(e){
				console.log(e)
			},
			// async getSubjectList() {
			// 	this.subjectList = []
			// 	// console.log(this.mechanism_id, this.formData.type_subject_id, this.formData.type_drive_id)
			// 	const data = await db.collection('mechanism-subject-list,subject-page')

			// 		.where({
			// 			mechanism_id: db.command.eq(this.mechanism_id),
			// 			['subject_id.type_subject']: db.command.eq(this.formData.type_subject_id),
			// 			['subject_id.type_drive_id']: db.command.in([this.formData.type_drive_id])
			// 		})
			// 		.field('_id,mechanism_id,subject_id,suject_id{_id,name,s_id,type_subject,type_drive_id}')
			// 		.limit(500)
			// 		.get()


			// 	if (data.result.data.length > 0) {
			// 		let subjectlist = data.result.data[0].subject_id
			// 		for (let s of subjectlist) {
			// 			this.subjectList.push({
			// 				value: s.s_id,
			// 				text: s.name
			// 			})
			// 		}
			// 	}
			// 	console.log(this.subjectList)
			// },
			async getSubjectList() {
				this.subjectList = []
				//console.log(this.mechanism_id, this.formData.type_subject_id, this.formData.type_drive_id)
				// 	const data = await db.collection('mechanism-subject-list,subject-page')

				// 		.where({
				// 			// mechanism_id: db.command.eq(this.mechanism_id),
				// 			'subject_id.type_subject': db.command.eq(this.formData.type_subject_id)
				// 			// ['subject_id.type_drive_id']: db.command.in([this.formData.type_drive_id])
				// 		})
				// 		.field('_id,mechanism_id,subject_id,suject_id{_id,name,s_id,type_subject,type_drive_id}')
				// 		.limit(500)
				// 		.get()

				const mesubjectList = await db.collection('mechanism-subject-list')
					.where({
						mechanism_id: db.command.eq(this.mechanism_id),
					}).limit(500)
					.getTemp();
				const subject = await db.collection('subject-page').where({
					type_subject: db.command.eq(this.formData.type_subject_id),
					type_drive_id: db.command.in([this.formData.type_drive_id])
				})
				.limit(500)
				.getTemp()
				const data = await db.collection(mesubjectList, subject).get()
				if (data.result.data.length > 0) {
					let subjectlist = data.result.data[0].subject_id
					for (let s of subjectlist) {
						this.subjectList.push({
							value: s.s_id,
							text: s.name
						})
					}
				}
				this.firstChange=true
			},

			setCertValue(value) {
				this.formData.type_cert_id = ''
				this.$nextTick(() => {
					for (let s of this.$refs.drive_udb.mixinDatacomResData) {
						if (s.value === value) {
							this.showCertText = s.type_cert_id[0].name
							this.formData.type_cert_id = s.type_cert_id[0].s_id
						}
					}
				})
			},
			/**
			 * 跳转应用管理的 list 页
			 */
			gotoAppList() {
				uni.navigateTo({
					url: '../app/list'
				})
			},
			gotoTagList() {
				uni.navigateTo({
					url: '../tag/list'
				})
			},
			gotoTagAdd() {
				uni.navigateTo({
					url: '../tag/add',
					events: {
						refreshCheckboxData: () => {
							this.$refs.checkbox.loadData()
						}
					}
				})
			},

			/**
			 * 触发表单提交
			 */
			async submitForm() {
				const result = await this.checkUser()
				if (result) {
					this.$refs.form.submit();
				}
			},
			async checkUser() {
				if (this.formData.username == '') {
					return
				}
				const user = await db.collection('uni-id-users').where({
						username: this.formData.username
					})
					.field('_id,username')
					.get()
				if (user.result.data.length > 0) {
					uni.showToast({
						title: '用户名已注册，请更换用户名',
						duration: 2000,
						icon: 'none'
					})
					return false
				} else {
					return true
				}
			},

			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail
				console.log(value)
				// 表单校验失败页面会提示报错 ，要停止表单提交逻辑
				if (errors) {
					return
				}
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				// 是否启用功能的数据类型转换， 0 正常， 1 禁用
				if (typeof value.status === "boolean") {
					value.status = Number(!value.status)
				}
				if (typeof value.fee_status === "boolean") {
					value.fee_status = Number(!value.fee_status)
				}
			
							value.subject_page_ids = this.formData.subject_page_ids

				value['mechanism_id'] = this.mechanism_id
				value['role'] = ['xueshen']
				value['dcloud_appid'] = ['__UNI__84671FB']
				
				this.$request('registerUser', value, {
					functionName: 'uni-id-cf'
				}).then(res => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					uni.navigateBack()
				}).catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(err => {
					uni.hideLoading()
				})
			},
			loadroles() {
				let where = {}
				if (this.roleList.length > 0) {
					where['role_id'] = db.command.in([this.roleList[0]])
				}
				db.collection('uni-id-roles').where(where).limit(500).get().then(res => {
					const roleIds = []
					console.log('role', res.result.data)
					this.roles = res.result.data.map(item => {
						roleIds.push(item.role_id)
						return {
							value: item.role_id,
							text: item.role_name
						}
					})
					if (roleIds.indexOf('admin') === -1 && this.roleList.length == 0) {
						this.roles.unshift({
							value: 'admin',
							text: '超级管理员'
						})
					}
				}).catch(err => {
					uni.showModal({
						title: '提示',
						content: err.message,
						showCancel: false
					})
				})
			}
		}
	}
</script>
<style>
	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}

	.require-bg .uni-easyinput {
		background: #f04e4eAA !important;
	}
</style>
